<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper" ref="myElement">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :span="8" >
                <a-form-item
                  label="检查时间"
                  :labelCol="{ style: 'width:115px' }"
                  :wrapperCol="wrapperCol"
                >
                  <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange1" :style="{width: '50%'}" v-model="TimeOn"/>
                  <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange2" :style="{width: '50%'}" v-model="TimeEnd"/>
                </a-form-item>
              </a-col>
              <a-col :span="6" >
                <a-form-item label="隐患单位" :labelCol="{ style: 'width:115px' }" required>
                  <a-tree-select
                    :style="{ width: selectWidth + 'px' }"
                    allowClear
                    showSearch
                    style="width:100%;"
                    tree-node-filter-prop="title"
                    v-model="queryParam.DangerOrganizationName"
                    :treeData="QHSEOrganizationTree"
                    v-if="QHSEOrganizationTree.length"
                    @change="handleOrganizationSelectChange"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择隐患单位"
                    :title="queryParam.DangerOrganizationName" />
                </a-form-item>
              </a-col>
              <a-col :span="6" >
                <a-form-item label="设备ERP编号" :labelCol="{ style: 'width:115px' }" :wrapperCol="wrapperCol" required>
                  <a-select allow-clear placeholder="请选择设备ERP编号" v-model="queryParam.ErpNo">
                    <a-select-option v-for="(item) in erpList" :key="item" :value="item">{{ item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="2" class="search-buttons">
                <a-button type="primary" @click="handleClick" v-if="hasPerm('hdv_qhse_d_compage')">查询</a-button>
              </a-col>
              <a-col :span="2" class="search-buttons">
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-card :bordered="false" style="margin-top: -5px;">
        <a-col :span="2" class="search-buttons" style="margin-left: -5px;">
          <a-button type="primary" @click="handleExport" :loading="batchExportLoading"><a-icon type="export"/>导出</a-button>
        </a-col>
        <a-col :span="4">
          <a-progress
            v-if="batchExportLoading"
            :percent="exportProgress"
            status="active"
          />
        </a-col>
        <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          :alert="null"
          :rowKey="(record) => record.qhseXyDangerId"
          :rowSelection="null"
          bordered
          style="margin-top: 20px"
        >
          <span slot="action" slot-scope="text, record">
            <a-button size="small" style="color:#389e0d;background-color: #f6ffed;border-color: #b7eb8f;">
              <a @click="$refs.DanDetail.edit(record)">
                <a-icon type="file-text" />
                详情
              </a>
            </a-button>
            <a-button size="small" style="color: #1d39c4;background-color: #f0f5ff;border-color: #adc6ff;" v-if="hasPerm('hdv_qhse_d_all_edit')">
              <a @click="editRecord(record)">
                <a-icon type="edit" /> 编辑
              </a>
            </a-button>
            <a-popconfirm
              placement="topRight"
              title="确认删除？"
              @confirm="() => singleDelete(record)"
            >
              <a-button size="small" style="color: #d4380d;background: #fff2e8;border-color: #ffbb96;" v-if="hasPerm('hdv_qhse_d_all_delete')">
                <a><a-icon type="delete" />删除</a>
              </a-button>
            </a-popconfirm>
          </span>
        </s-table>
        <dan-detail ref="DanDetail" @ok="handleOk" />
        <dan-edit-form ref="DanEditForm" @ok="handleOk"></dan-edit-form>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
import { STable, XCard, XDown, DanDetail, DanEditForm } from '@/components'
import { Empty } from 'ant-design-vue'
import { getComPageErp, getExportToExcelErp } from '@/api/modular/system/QHSEHazardQuery'
import { QHSEDangerDelete } from '@/api/modular/system/QHSEDanger'
import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
import { getErplist } from '@/api/modular/system/QHSEErpManager'
import moment from 'moment'
import { mapGetters } from 'vuex'
export default {
  components: {
    XDown,
    XCard,
    STable,
    DanDetail,
    DanEditForm
  },
  data() {
    return {
      labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
      // 获取参数
      queryParam: {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
      },
       // 导出参数
      exportParam: {},
      exportProgress: 0,
      defaultExpandedKeys: [],
      secondOraName: {
          id: ''
        },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '检查时间',
          dataIndex: 'checkDate',
          customRender: (text, record) => {
            if (record.checkDate) {
              const dateParts = record.checkDate.split('T')[0].split('-')
              return `${dateParts[0]}-${dateParts[1]}-${dateParts[2]}`
            }
            return ''
          }
        },
        {
          title: '检查单位',
          dataIndex: 'checkOrganizationName',
          width: 200,
          customRender: (text) => (
            <a-tooltip title={text}>
              {text.length > 10 ? text.substr(0, 10) + '...' : text}
            </a-tooltip>
          )
        },
        {
          title: '检查人员',
          dataIndex: 'checkName'
        },
        {
          title: '隐患单位',
          dataIndex: 'organizationName',
          width: 200,
          customRender: (text) => (
            <a-tooltip title={text}>
              {text.length > 12 ? text.substr(0, 12) + '...' : text}
            </a-tooltip>
          )
        },
        {
          title: '隐患区域',
          dataIndex: 'location',
          customRender: (text) => (
          <a-tooltip title={text}>
          {text.length > 5 ? text.substr(0, 5) + '...' : text}
          </a-tooltip>
        )
        },
        {
          title: '隐患级别',
          dataIndex: 'dangerType',
          customRender: function(text) {
            if (text === '重大隐患') {
              return <span style={{ color: 'red' }}>{text}</span>
            } else if (text === '较大隐患') {
              return <span style={{ color: 'orange' }}>{text}</span>
            } else {
              return <span style={{ color: 'rgb(227, 227, 70)' }}>{text}</span>
            }
          }
        },
        {
          title: '隐患状态',
          dataIndex: 'status',
          customRender: function(text) {
            if (text === '已整改') {
              return <span style={{ color: 'rgb(34, 173, 34)' }}>{text}</span>
            } else {
              return <span style={{ color: 'red' }}>{text}</span>
            }
          }
        },
        {
          title: '作业项目',
          dataIndex: 'workItem'
        },
        {
          title: '隐患描述',
          dataIndex: 'description',
          customRender: (text) => (
            <a-tooltip title={text}>
              {text.length > 5 ? text.substr(0, 5) + '...' : text}
            </a-tooltip>
          )
        },
        {
          title: 'ERP编号',
          dataIndex: 'erpNo'
        }
      ],
      loadData: (parameter) => {
        return getComPageErp(Object.assign(parameter, this.queryParam)).then((res) => {
        //   console.log(this.queryParam)
        //   console.log(res.data)
          return res.data
        })
      },
      batchExportLoading: false,
      TimeEnd: moment(new Date(), 'YYYY-MM-DD'),
      TimeOn: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
      form: this.$form.createForm(this),
      erpList: [],
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'workflowId',
        value: 'id',
        parentId: 'parentId'
      },
      selectWidth: 200,
      QHSEOrganizationTree: [],
      queryId: {
        id: ''
      }
    }
  },
  computed: {
      ...mapGetters(['userInfo'])
    },
  mounted() {
    window.addEventListener('resize', this.handleResize())
    this.handleResize()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize())
  },
  created() {
    this.getQHSEOrganizationTree()
    this.columns.push({
      title: '操作',
      width: '250px',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    })
  },
  methods: {
    getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('tree:', res.data)
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.QHSEOrganizationTree = res.data
        if (res.data.length === 0) {
          this.secondOraName.id = '机关总部'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            this.QHSEOrganizationTree = res.data
          })
        }
        })
      },
    // 选择隐患单位
    handleOrganizationSelectChange(val, opt, extra) {
      if (extra.triggerNode === undefined) {
        this.queryParam.DangerOrganizationName = null
        this.queryParam.DangerOrganizationId = null
      } else {
        const option = extra.triggerNode._props.title
        this.queryParam.DangerOrganizationName = option
        this.queryParam.DangerOrganizationId = extra.triggerNode._props.value
        this.queryId.id = this.queryParam.DangerOrganizationId
        getErplist(this.queryId).then(res => {
          console.log('res', res)
          this.erpList = res.data
        })
      }
    },
    editRecord(record) {
      // console.log('record', record)
      if (record.checkOrganizationId === this.userInfo.currentOrganizationId) {
        this.$refs.DanEditForm.edit(record)
      } else {
        this.$message.warning('当前用户非本条数据的录入者，不可编辑！')
      }
    },
    singleDelete(record) {
      if (record.checkOrganizationId === this.userInfo.currentOrganizationId) {
        const param = [{ 'id': record.qhseXyDangerId }]
        this.QHSEDangerDelete(param)
      } else {
        this.$message.warning('当前用户非本条数据的录入者，不可删除！')
      }
    },
    /**
     * 删除违章记录
     */
     QHSEDangerDelete(param) {
      QHSEDangerDelete(param)
        .then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        })
        .catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
    },
    handleResize() {
      var myElement = this.$refs.myElement
      if (myElement) {
        var width = myElement.offsetWidth
        this.selectWidth = (width - 12 * 6) / 4 - 115
      }
    },
    handleClick() {
      if ((!this.TimeOn || !this.TimeEnd || !this.queryParam.ErpNo) && (this.TimeOn || this.TimeEnd)) {
        this.$message.warning('请填写完整的查询信息！')
      } else {
        this.exportParam = { ...this.queryParam }
        this.$refs.table.refresh(true)
      }
    },
    onChange1(date, dateString) {
      // console.log(dateString, date)
      if (this.queryParam.TimeEnd && dateString) {
        if (dateString > this.queryParam.TimeEnd) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD')
        } else {
          this.queryParam.TimeOn = dateString
        }
      } else {
        this.queryParam.TimeOn = dateString
      }
    },
    onChange2(date, dateString) {
      if (this.queryParam.TimeOn && dateString) {
        if (this.queryParam.TimeOn > dateString) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
        }
      } else {
        this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
      }
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    handleExport(parameter) {
      this.batchExportLoading = true
      this.exportProgress = 0 // 重置进度
      this.exportParam = { ...this.queryParam }

      const interval = setInterval(() => {
        if (this.exportProgress < 90) { // 进度最高到 90%，剩下的 10% 在下载完成时更新
          this.exportProgress += 10
        }
      }, 500)
      getExportToExcelErp(Object.assign(parameter, this.exportParam))
        .then(response => {
          clearInterval(interval) // 清除定时器
          this.exportProgress = 100 // 导出完成后，设置进度为 100%
          // 创建下载链接
          const downloadLink = document.createElement('a')
          downloadLink.href = window.URL.createObjectURL(response.data)
          // 设置下载链接的属性
          downloadLink.download = '设备全生命周期_' + new Date().toISOString() + '.xlsx'
          downloadLink.target = '_blank'
          // 在下载链接的 click 事件处理程序中停止加载状态
          downloadLink.addEventListener('click', () => {
            this.batchExportLoading = false
          })
          // 触发下载
          downloadLink.click()
        })
        .catch(error => {
          clearInterval(interval) // 清除定时器
          console.error('下载失败:', error)
          this.batchExportLoading = false
        })
    },
    reset() {
      this.queryParam = {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD'),
        ErpNo: ''
      }
      this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
      this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
    }
  }
}
</script>
<style lang="less" scoped>
  /deep/.ant-table-tbody tr:nth-child(2n) {
    background-color:#f5f5f5;
  }
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
.scrollable-select {
  max-height: 200px; /* 根据需要设置最大高度 */
  overflow-y: auto;
}
</style>
